//
//  ZMRightTableView.swift
//  LoveBeen
//
//  Created by pg on 2017/8/7.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import SDWebImage
class ZMRightTableView: UITableView {

    //闭包向外传递cell的滚动事件
    var rightTableViewScroll:((_ indexpath: IndexPath)->())?
    
    
    
    
    
    var categoryModelArray: [ZMCategoriesModel]?{
        didSet{
            
           self.reloadData()
        }
        
    }
    
    var productModelArray:[ZMProductsModel]?{
        didSet{
            
            self.reloadData()
        }
    }
    
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        
        delegate = self
        dataSource = self
        
         estimatedRowHeight = 100
        //注册cell
        register(rightTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    


}

extension ZMRightTableView : UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return categoryModelArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return categoryModelArray![section].produceModels?.count ?? 0
        
      //  return productModelArray?.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! rightTableViewCell
        
        cell.productModel = categoryModelArray![indexPath.section].produceModels![indexPath.row] //productModelArray![indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        //获取点击cell对应的模型
        let model = self.categoryModelArray![indexPath.section].produceModels![indexPath.row]
        //通知向外部传递cell的点击事件
        NotificationCenter.default.post(name: NSNotification.Name(ShowProductCellDidSelectedNotification), object: nil, userInfo: ["model": model,"indexpath": indexPath])
    }
    
    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if tableView.isDragging || tableView.isTracking || tableView.isDecelerating{
        
        //获取当前显示的所有的cell 的indexpath
        let indexpathArray = self.indexPathsForVisibleRows

        
        
        //获取第一个元素
        let firstPath: IndexPath = (indexpathArray?.first)!
        //右侧滚动到第几组,,左侧就滚动到第几行
        let indexLeft = IndexPath(row: firstPath.section, section: 0)
        
        rightTableViewScroll?(indexLeft)
        
        }
    }
    
    
}

class rightTableViewCell: UITableViewCell {
    
  
    
    var productModel: ZMProductsModel?{
        didSet{
            
            iconView.sd_setImage(with: (URL(string:(productModel?.img!)!))!, placeholderImage: UIImage(named: "v2_placeholder_square"))
            titleLabel.text = productModel?.name
            specificsLabel.text = productModel?.specifics
            
            priceLabel.text = productModel?.price
            market_priceLabel.text = productModel?.market_price
            
            addToShoppingCarView.count = productModel?.buyNum ?? 0
        }
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载配图
    fileprivate lazy var iconView : UIImageView = {
       
        let icon = UIImageView()
        
        
        return icon
    }()
    //懒加载   精选  jingxuan.png
    fileprivate lazy var choicenessView : UIImageView = {
        
        let icon = UIImageView(image: #imageLiteral(resourceName: "jingxuan.png"))
        
//        icon.sizeToFit()
        return icon
    }()
    //懒加载   买一赠送  buyOne.png
    fileprivate lazy var takeFreeView : UIImageView = {
        
        let icon = UIImageView(image: #imageLiteral(resourceName: "buyOne.png"))
        
       // icon.sizeToFit()
        return icon
    }()
   //懒加载   标题
    fileprivate lazy var titleLabel : UILabel  = {
        let label = UILabel(text: "正在加载数据", fontSize: 15, textColor: UIColor.darkGray)
        
        label.sizeToFit()
        return label
    
    }()
    //懒加载 规格说明
    fileprivate lazy var specificsLabel : UILabel  = {
        let label = UILabel(text: "说明", fontSize: 13, textColor: UIColor.lightGray)
        
        label.sizeToFit()
        return label
        
    }()
    //懒加载 现价
    fileprivate lazy var priceLabel : UILabel  = {
        let label = UILabel(text: "现价", fontSize: 14, textColor: UIColor.red)
        
        label.sizeToFit()
        return label
        
    }()
    //懒加载 超时价格  market_price
    fileprivate lazy var market_priceLabel : UILabel  = {
        let label = UILabel(text: "原价", fontSize: 14, textColor: UIColor.lightGray)
        
        let line: UIView = UIView()
        label.addSubview(line)
        
        line.backgroundColor = UIColor.lightGray
        
        line.snp.makeConstraints({ (make) in
             make.center.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(1)
        })
        
        
        
        label.sizeToFit()
        return label
        
    }()
    //懒加载  加号 减号 视图
    fileprivate lazy var addToShoppingCarView: ZMAddToShoppingCarView  = {
       
        let view = ZMAddToShoppingCarView()
       
        
        
        return view
    }()
    //初始化UI
    private func setupUI(){
       // contentView.backgroundColor = UIColor.lightGray

        //添加图片
        contentView.addSubview(iconView)
        iconView.snp.makeConstraints { (make) in
            make.top.leading.bottom.equalTo(contentView)
            make.width.height.equalTo(100).priority(.high)
           
        }
        //添加精选
        contentView.addSubview(choicenessView)
        choicenessView.snp.makeConstraints { (make) in
            make.top.equalTo(iconView)
            make.leading.equalTo(iconView.snp.trailing).offset(5)
            make.width.equalTo(40)
            make.height.equalTo(20)
        }
       contentView.addSubview( takeFreeView)
        takeFreeView.snp.makeConstraints { (make) in
            make.top.equalTo(choicenessView.snp.bottom).offset(5)
            make.leading.equalTo(choicenessView)
            make.width.equalTo(50)
            make.height.equalTo(20)
        }
        //添加标题
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(iconView)
            make.leading.equalTo(choicenessView.snp.trailing).offset(5)
            
        }
        //添加  规格说明
        contentView.addSubview(specificsLabel)
        specificsLabel.snp.makeConstraints { (make) in
            make.top.equalTo(takeFreeView.snp.bottom).offset(5)
            make.leading.equalTo(takeFreeView)
        }
        //添加  现价
        contentView.addSubview(priceLabel)
        priceLabel.snp.makeConstraints { (make) in
            make.top.equalTo(specificsLabel.snp.bottom).offset(5)
            make.leading.equalTo(specificsLabel)
        }
        //原价  market_priceLabel
        contentView.addSubview(market_priceLabel)
        market_priceLabel.snp.makeConstraints { (make) in
            make.top.equalTo(priceLabel)
            make.leading.equalTo(priceLabel.snp.trailing).offset(5)
        }
        //添加到购物车到的view
        contentView.addSubview(addToShoppingCarView)
        addToShoppingCarView.snp.makeConstraints { (make) in
            make.trailing.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
    
        }
        
        //添加商品到购物车按钮点击回调 代码块
        addToShoppingCarView.addToShoppintCarViewButtonClickClosure = {[unowned self] (isAddButton) in
            if isAddButton {
                //获取当前cell的imageview的中心点坐标
                let iconCenter: CGPoint =  self.iconView.center
                //将坐标转到window上
                let covernPoint = self.contentView.convert(iconCenter, to: keywindow)
                //发送添加通知
                NotificationCenter.default.post(name: NSNotification.Name(AddToShoppingCarViewNotification), object: nil, userInfo: ["model": self.productModel!,"point": covernPoint,"image": self.iconView.image!])
                
            }else
            {
               //发送添加通知
                NotificationCenter.default.post(name: NSNotification.Name(SubFromShoppingCarViewNotification), object: nil, userInfo: ["model": self.productModel! ])
            }
            self.addToShoppingCarView.count = self.productModel?.buyNum ?? 0
        }
        
    }
}
//cell 中的增加和减少购物按钮的view
class ZMAddToShoppingCarView: UIView{
    
    //闭包  向外传递按钮单击事件
    var addToShoppintCarViewButtonClickClosure:((_ isAddBtn:Bool)->())?
    
    
    var count: Int = 0{
        didSet{
            
            if count == 0 {
                HiddenLeftView(isHidden: true)
            }else{
                HiddenLeftView(isHidden: false)
            }
            
            countLabel.text = "\(count)"
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //   + 按钮
    fileprivate lazy var addButton: UIButton = {
       let btn = UIButton()
        btn.addTarget(self, action: #selector(addBtnClick), for: UIControlEvents.touchUpInside)
        btn.setBackgroundImage(#imageLiteral(resourceName: "v2_increase"), for: .normal)
        return btn
    }()
    //   - 按钮
    fileprivate lazy var MulButton: UIButton = {
        let btn = UIButton()
        
        //单击事件
        btn.addTarget(self, action: #selector(MulBtnClick), for: UIControlEvents.touchUpInside)
        
        btn.setBackgroundImage(#imageLiteral(resourceName: "v2_reduce"), for: .normal)
        return btn
    }()
    //   count
    fileprivate lazy var countLabel:UILabel = {
       
        let label = UILabel(text: "0", fontSize: 13, textColor: UIColor.darkGray)

        label.textAlignment = .center

        return label
    }()
    
    
    private func setupUI(){
        
     
        //添加 +按钮 v2_increase
        addSubview(addButton)
        addButton.snp.makeConstraints({ (make) in
            make.top.trailing.bottom.equalToSuperview()
            make.width.height.equalTo(20)
        })
        
        
        //添加  -  v2_reduce
        addSubview(MulButton)
        MulButton.snp.makeConstraints({ (make) in
            make.top.leading.bottom.equalToSuperview()
            make.width.height.equalTo(20)
        })
        
        //添加中间label
        addSubview(countLabel)
        countLabel.snp.makeConstraints({ (make) in
            make.top.equalTo(addButton)
            make.trailing.equalTo(addButton.snp.leading)
            make.leading.equalTo(MulButton.snp.trailing)
            make.width.equalTo(20)
        })

        //初始状态 隐藏view
        HiddenLeftView(isHidden: true)
    }
    
    //隐藏减号按钮和技术label
    func HiddenLeftView(isHidden: Bool){
        
       MulButton.isHidden = isHidden
        countLabel.isHidden = isHidden
        
    }
   
    
    
    //MARK:- 添加按钮单击事件
    @objc  private func addBtnClick(){
    
        
        addToShoppintCarViewButtonClickClosure?(true)
    }
    //MARK:- 减少按钮单击事件
   @objc private func MulBtnClick(){
    
       addToShoppintCarViewButtonClickClosure?(false)
    }
    
    
}



